<template>
	<view class="page tab-page">
		<view class="mask" v-if="dropMenuVisible" @click="dropMenuVisible = !dropMenuVisible"></view>
		<GlobalPanel />
		<!-- #ifdef APP-PLUS -->
		<view v-if="showNotice">
			<topNotice message="用于根据你的定位推荐并且加入三个附近的官方群,或帮助你在发布信息中展示位置" v-if="showNotice" title="位置权限使用说明"></topNotice>
		</view>
		<!-- #endif -->
		<view class="nav-header">
			<!-- #ifndef APP-PLUS -->
			<up-navbar :auto-back="false" title-width="200" placeholder rightIcon="more-dot-fill" bgColor="transparent"
				:fixed="false">
			<!-- #endif -->
				<!-- #ifdef APP-PLUS -->
				<up-navbar :auto-back="false" height="20px" title-width="200" rightIcon="more-dot-fill"
					bgColor="transparent" :fixed="false">
				<!-- #endif -->
					<template v-slot:left>
						<text class="title">消息</text>
					</template>
					<template v-slot:right>
						<slot name="right">
							<view class="create-group">
								<!-- 1111 -->
							</view>
							<view class="nav-more" @click="dropMenuVisible = !dropMenuVisible">
								<uni-icons type="plus" size="32"></uni-icons>
								<view style="margin-top: 60rpx;margin-left: -8rpx;">
									<drop-menu @action="action" :list="menuList" v-model="dropMenuVisible" />
								</view>
							</view>
						</slot>
					</template>
				</up-navbar>
				<view class="search">
					<up-search placeholder="搜索" v-model="searchText" :clearabled="true" :showAction="false"
						bg-color="#ffffff" search-icon-color="#474a52" placeholder-color="#82868d"
						height="40"></up-search>
				</view>
		</view>
		<view style="margin-top: 20vh;" v-if="loading">
			<up-loading-icon text="正在努力加载中~" textSize="18"></up-loading-icon>
		</view>
		<view v-if="!loading && chatList.length == 0">
			<up-empty :icon="getResource('/icon/empty-message.svg')" text="消息为空">
			</up-empty>
		</view>
		<scroll-view class="scroll-bar" v-else-if="!loading && chatList" scroll-with-animation="true" scroll-y="true">
			<chat-panel :chat-list="chatList" :type="chatStore.chatType.PRIVATE"
				:source-type="$enums.privateMessageType.PRIVATE"></chat-panel>
		</scroll-view>
	</view>
	<view v-if="showTips" class="footer" @click="toMineInfo">
		<view class="footer-content">
			<view class="left-section">
				<up-icon name="volume" class="icon-left"></up-icon>
				<text style="color:#ED6A0C; margin-left: 30px;">完善您的个人信息可使用完整功能</text>
			</view>
			<up-icon name="arrow-right" class="icon-right"></up-icon>
		</view>
	</view>
	<!-- #ifdef APP-PLUS -->
	<view>
		<custom-tabbar :selected="0" :chat="unreadCount"></custom-tabbar>
	</view>
	<!-- #endif -->

<!-- 腾讯上架小程序 -->
<!-- 	<view>
		<up-modal title="注册成功" @confirm="confirm" @cancel="cancel" :show="isTips" showCancelButton closeOnClickOverlay
			cancelText="登录" confirmText="修改密码" contentTextAlign="left">
			<view class="main-layout">
				<view class="first-row">{{ tips }}</view>
				<view class="second-row">密码：{{ passwordText }}
					<svg-icon icon="copy" class="code" @click="copyText(passwordText)"></svg-icon>
				</view>
			</view>
		</up-modal>
	</view> -->

</template>

<script>
	import GlobalPanel from '@/components/global-panel/global-panel.vue'
	// #ifdef APP-PLUS
	import topNotice from '@/components/topNotice/topNotice.vue'; // 引入自定义组件
	// #endif
	// #ifdef APP-PLUS
	import permision from "@/js_sdk/wa-permission/permission.js"
	// #endif
	import {
		getRegeoData
	} from '@/common/locationUtils.js';
	import {
		execShareData
	} from '@/utils/qrcode';
	export default {
		components: {
			GlobalPanel
		},
		data() {
			return {
				isLogin: true,
				dropMenuVisible: false,
				menuList: [{
					icon: 'Default-2',
					text: '发起群聊'
				}, {
					icon: 'Default-3',
					text: '添加官方群'
				}, {
					icon: 'Default-8',
					text: '添加好友'
				}, {
					icon: 'Default-4',
					text: '扫一扫'
				}, ],
				searchText: "",
				location: '',
				show: false,
				province: "广东省",
				city: "广州市",
				area: "天河区",
				areaCode: "440106",
				addressData: {
					name: '',
					phone: '',
					address: '',
					moreAddres: '',
					isdefult: 0
				},
				isShow: true,
				tips: '',
				isTips: false,
				passwordText: '',
				showNotice: false, //是否显示通知信息
			}
		},
		methods: {
			/**
			 * 导航栏下拉菜单选中事件
			 */
			action(i, item) {
				if (i === 0) {
					uni.navigateTo({
						url: "/pageSubOne/group/group-add?groupType=0"
					});
				} else if (i === 1 || i === 2) {
					uni.navigateTo({
						url: "/pageSubOne/friend/friend-add?sourceType=0"
					});
				} else if (i === 3) {
					this.scanCode();
				}
			},
			scanCode() {
				// #ifdef MP-WEIXIN || APP-PLUS
				console.log("微信直接扫码");
				uni.scanCode({
					// scanType: ['QR_CODE'], //条形码
					success: function(res) {
						execShareData(res)
					}
				});
				// #endif
				// #ifndef MP-WEIXIN || APP-PLUS
				uni.navigateTo({
					url: "/pageSubOne/scan-code/scan-code"
				})
				// #endif
			},
			openPicker() {
				console.log('执行打开地址选择器')
				this.show = true
			},
			changeClick(value, value2, value3, value4) {

				console.log('地址选择器 = ' + value + value2 + value3 + value4);

				this.province = value;
				this.city = value2;
				this.area = value3;
				this.areaCode = value4;
			},
			onhideShow() {
				this.show = false
				console.log('执行了关闭地址选择器')
			},
			//选中省市区
			onsetCity(e) {
				let data = e.detail.target.dataset;
				let address = data.province + data.city + data.area;
				this.show = false
				this.addressData.address = address
			},
			onGetLocation() {
				uni.navigateTo({
					url: "/pageSubOne/chat/selectMap"
				})
			},
			goNotice() {
				uni.navigateTo({
					url: "/pageSubOne/notice/notice"
				})
			},
			refreshUnreadBadge() {
				if (this.unreadCount > 0) {
					uni.setTabBarBadge({
						index: 0,
						text: this.unreadCount + ""
					})
				} else {
					uni.removeTabBarBadge({
						index: 0,
						complete: () => {}
					})
				}
			},
			// 跳转到修改信息页面
			toMineInfo() {
				uni.navigateTo({
					url: `/pageSubOne/mine/mine-info`
				})
			},
			showToast() {
				this.$refs.uToastRef.show()
			},
			// 获取地理位置
			getLocation() {
				// #ifndef APP-PLUS
				getRegeoData().then(regionData => {
					console.log(regionData)
					this.$http({
						url: '/group/joinOfficialGroupByCode',
						data: regionData,
						method: 'POST'
					}).then(res => {
						getApp().$vm.init()

					})
				})
				// #endif


				// #ifdef APP-PLUS
				
				// 单独为vivo设计的版本
				// let regionData = {
				// 	code: "441900",
				// 	streetName: "大岭山镇"
				// }
				// this.$http({
				// 	url: '/group/joinOfficialGroupByCode',
				// 	data: regionData,
				// 	method: 'POST'
				// }).then(res => {
				// 	getApp().$vm.init()
				// })
				
				this.showNotice = true;
				const self = this;
				
				uni.getLocation({
					success: function(res) {
						getRegeoData().then(regionData => {
							self.$http({
								url: '/group/joinOfficialGroupByCode',
								data: regionData,
								method: 'POST'
							}).then(res => {
								getApp().$vm.init()
							})
						})
						self.showNotice = false;
					},
					fail: function(err) {
						console.log("err", err)
						if (err.errMsg === "getLocation:fail 获取定位权限失败") {
							self.requestAndroidPermission("android.permission.ACCESS_FINE_LOCATION")
							self.showNotice = false;
						} else {
							console.log('获取位置失败：', err);
							self.showNotice = false;
						}
					}
				});
				// #endif
			},
			// #ifdef APP-PLUS
			// vue的method里编写如下代码
			async requestAndroidPermission(permisionID) {
				var result = await permision.requestAndroidPermission(permisionID)
				var strStatus
				if (result == 1) {
					strStatus = "已获得授权"
				} else if (result == 0) {
					strStatus = "未获得授权"
				} else {
					// 定位权限未授权，引导用户去设置中授权
					uni.showModal({
						title: '提示',
						content: '未授权定位权限，请在系统设置中打开定位权限',
						success: function(modalRes) {
							if (modalRes.confirm) {
								// 引导用户到设置页
								permision.gotoAppPermissionSetting()
							}
						}
					});
					// strStatus = "被拒绝权限，将跳转设置重新授权"
					// permision.gotoAppPermissionSetting()
				}
				if (result == 1 || result == 0)
					uni.showModal({
						content: permisionID + strStatus,
						showCancel: false
					});
			},
			// #endif
			anonymousLogin() {

				// 用户匿名注册之后 弹出

				this.$http({
					url: '/anonymousRegister',
					method: 'POST'
				}).then(res => {
					// 匿名登录之后 把token放到storage里
					uni.setStorageSync("loginInfo", res.token);
					this.userStore.loadUser()



					const userName = res.userinfo.userName
					const password = res.userinfo.password
					uni.setStorageSync("userName", userName);
					uni.setStorageSync("password", password);
					this.passwordText = password

					this.tips = `您注册的用户账号为:${userName},密码为:${password},请您尽快修改密码!`
					this.isTips = true


				});
			},
			cancel() {
				console.log("cancel")
				this.isTips = false
			},
			confirm() {
				console.log("confirm")
				uni.navigateTo({
					url: `/pageSubOne/mine/mine-password?password=${this.passwordText}`
				})
				this.isTips = false
			},
			copyPassword() {
				console.log("copyPassword")
				const text = this.passwordText
				uni.setClipboardData({

					data: text.toString(),
					success: function(res) {
						console.log('复制的密码：', text);
						uni.showToast({
							title: '复制密码成功',
						});
					}
				});
			}

		},
		computed: {
			showTips() {
				return this.userStore.userInfo.isTmp
			},
			chatList() {
				this.chatStore.resetPrivateChats()
				return this.chatStore.privateChats.filter(e => e.showName && e.showName.includes(this.searchText))
			},
			unreadCount() {
				let count = 0;
				this.chatList.forEach(chat => {
					if (!chat.delete) {
						count += chat.unreadCount;
					}
				})
				//this.chatList.push({headImage:'',type:"GROUP",showName:'友星缘助手',targetId:""})    
				console.log(this.chatList)					 
				return count;
			},
			loading() {
				return this.chatStore.loadingGroupMsg || this.chatStore.loadingPrivateMsg
			},
			addressInfo() {
				return this.chatStore.addressInfo;
			}
		},
		watch: {
			unreadCount(newCount, oldCount) {
				this.refreshUnreadBadge();
			}
		},
		onShow() {

			if (this.userStore.userInfo.isTmp !== undefined) {
				this.isLogin = this.userStore.userInfo.isTmp
			}
			uni.setStorageSync('location', this.chatStore.addressInfo)
			this.location = uni.getStorageSync('location')
			// 刷新运财宝
			// this.triggerRefresh();
			this.refreshUnreadBadge();


		},
		onLoad() {
			const loginInfo = uni.getStorageSync("loginInfo")
			// #ifndef APP-PLUS
			if (!Boolean(loginInfo)) {
				console.log('调用匿名注册方法')
				this.anonymousLogin()
			}
			// #endif
			this.getLocation()
			this.noticeStore.clear()
			// 使用 setTimeout 延迟执行
			const self = this
			setTimeout(() => {
				self.noticeStore.loadNotice()
			}, 2000);


			// #ifdef APP-PLUS
			uni.hideTabBar()
			// #endif
		}
	}
</script>

<style scoped lang="scss">
	.page {
		height: calc(100vh - 125px) !important;
	}

	.nav-header {
		// background: linear-gradient(to bottom, rgba(210, 233, 237, 1) 0%, #eff4ff 40%, #eff4ff 100%);
		background-image: url('https://file.dgyxy.com/resource/bgDefault.png');
		background-size: 100% 100%;
		background-repeat: no-repeat;

		.title {
			font-size: 40rpx;
			font-weight: bold;
		}

		.search {
			padding-bottom: 20rpx;
			height: 70px;
			display: flex;
			align-items: center;
			justify-content: center;
			width: 90%;
			margin: 0 auto;

			:deep(.u-search__content) {
				border-radius: 12px !important;
			}
		}
	}

	.tab-page {
		position: relative;
		display: flex;
		flex-direction: column;

		.mask {
			// background-color: #000;
			// opacity: 0.3;
			position: fixed;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			z-index: 1
		}

		.pt-notice {
			width: 100%;

			.notice {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 10rpx 20rpx;

				.notice-left {
					display: flex;
					align-items: center;
					font-size: 30rpx;

					text {
						margin-right: 5rpx;
					}

					.notice-img {
						width: 40rpx;
						height: 40rpx;
					}
				}

				.notice-right {
					width: 400rpx;
					display: flex;
					align-items: center;

					text {
						font-size: 25rpx;
						color: #989898;
						display: -webkit-box;
						-webkit-line-clamp: 1;
						-webkit-box-orient: vertical;
						overflow: hidden;
						text-overflow: ellipsis;
					}
				}
			}
		}

		.nav-loc {
			display: flex;
			justify-content: center;
			align-items: center;
			cursor: pointer;

			.loc-text {
				color: #0a6cff;
				font-size: 28rpx;
			}
		}

		.nav-more {
			cursor: pointer;
			z-index: 2;
			display: flex;
			align-items: center;
			justify-content: flex-end;
		}

		.chat-tip {
			position: absolute;
			top: 400rpx;
			padding: 50rpx;
			line-height: 50rpx;
			text-align: left;
			color: darkblue;
			font-size: 30rpx;
		}

		.more-qun {
			font-size: 24rpx;
			text-align: right;
			color: #3b82f6;
		}


		.scroll-bar {
			flex: 1;
			height: 100%;
		}
	}

	.footer {
		position: fixed;
		/* #ifdef APP-PLUS */
		bottom: 180rpx;
		/* #endif */
		/* #ifndef APP-PLUS */
		bottom: 0;
		/* #endif */
		/* 固定在页面底部 */
		width: 97%;
		padding: 10px;
		background-color: #FFFBE8;
		/* 背景颜色可根据需要调整 */
		z-index: 1;
		/* 确保 footer 在内容之上 */
		box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
		/* 添加阴影效果，使其更明显 */
	}

	.footer-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		/* 使左右两部分对齐 */
		width: 100%;
		/* 确保内容容器占据整个宽度 */
	}

	.left-section {
		display: flex;
		align-items: center;
	}

	.icon-left {
		margin-left: 30rpx;
		margin-right: 10rpx;
		/* 调整图标与文字之间的距离 */
	}

	.icon-right {
		// margin-left: auto; /* 使图标靠右对齐 */
	}

	.main-layout {
		width: 100%;
	}

	.first-row {
		text-align: center;
		padding: 10px;
		border-bottom: 1px solid #ccc;
	}

	.second-row {
		display: flex;
		text-align: left;
		padding: 10px;
		border-bottom: 1px solid #ccc;
	}

	.code {
		margin-left: 30rpx;
		vertical-align: middle;
		/* 调整垂直对齐方式 */
		width: 70rpx;
		height: 50rpx;
	}
</style>